//
//  FileIO.cpp
//  sad
//
//  Created by Christopher Kemsley on 2/11/12.
//  Copyright (c) 2012 iAppolopolis. All rights reserved.
//

#include "FileIO.hpp"
#include <fstream>
#include <iostream>

using namespace Sim ;


std::string const&	FileIO :: contentsOfURL	( URL const & url )
	{
	std::string & str	=	_cache() [url] ;
	if ( str.size() == 0 )
		{
		_fetchURL(url,str) ;
		}
	return str ;
	}

void	FileIO :: mapVirtualFile	( URL const & url , std::string const & contents )
	{
	_cache()[url] = contents ;
	}

std::map<URL,std::string>&	FileIO :: _cache ()
	{
	static std::map<URL,std::string> m ;
	return m ;
	}

void		FileIO :: _fetchURL	( URL const & url , std::string & str )
	{
	if ( url.scheme() != "file" )
		return ;
	if ( url.host() != "localhost" )
		return ;
	
	
	std::ifstream stream;
	stream.open		( url.absolutePath().c_str() , std::ifstream::in ) ;
	std::cout << "Opening " << url.absolutePath() << "\n" ;
	
	// get length of file:
	stream.seekg (0, std::ios_base::end);
	size_t length = stream.tellg();
	
	if ( length != 0 && length != -1 )
		{
		stream.seekg (0, std::ios_base::beg);
		
		// allocate memory:
		char* buffer = new char [length];
		
		// read data as a block:
		stream.read (buffer,length);
		
		// append the data
		str . append ( buffer , length ) ;
		
		delete [] buffer ;
		}
	
	stream.close();
	}
